<template>
  <div class="aside-container" ref="fullscreenDiv" >
    <el-container>
      <el-main class="main_cont" id="map-board">

      </el-main>
      <div :class="isFullscreen?'input-item-total-full-screen':'input-item-total-full-screen-cancel'">
        <div>
          <span style="color: #fff;line-height: 30px;font-size: 16px">信息统计</span>
          <div>
            <span class="label">车辆总数:</span><span class="itemValue"> {{carDevCount.carCount}} 辆</span>
          </div>
          <div>
            <span class="label">在线总数:</span><span class="itemValue"> {{carDevCount.onlineCount}} 辆</span>
          </div>
        </div>
      </div>
      <div ref="infoWindow" v-show="infoWindowShow">
        <vehicleInfoWindow :info="info" @parentHandleVideo="parentHandleVideo"></vehicleInfoWindow>
      </div>
      <div ref="videoWindow" v-show="videoWindowShow">
        <videoInfoWindow></videoInfoWindow>
      </div>
      <div :class="isFullscreen?'refresh-full-screen':'refresh-full-screen-cancel'" >
         <span style="cursor:pointer;" @click="refreshClick">
              <svg-icon icon-class="refresh" />
          </span>
      </div>
      <div :class="isFullscreen?'full-screen':'full-screen-cancel'">
          <span style="cursor:pointer;" @click="screenfullClick">
              <svg-icon :icon-class="isFullscreen?'video-full-screen-cancel':'fullscreen'" />
          </span>
      </div>
    </el-container>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import {gaodeUtil} from "@/api/tool/gaodeUtil";
import {getAllCarDev, getOnlineCarDev} from "@/api";
import vehicleInfoWindow from "@/views/components/exgRun/vehicleInfoWindow";
import videoInfoWindow from "@/views/components/exgRun/videoInfoWindow";
import screenfull from "screenfull";
import {carDevAndVedioPlay, FLVPlayer} from "@/api/buss/realTimeVedio";
import $ from "jquery";

export default {
  name: "Index",
  components: {
    vehicleInfoWindow,
    videoInfoWindow
  },
  data() {
    return {
      maxLng: 0,//最大经度
      minLng: 1000,//最小经度
      maxLat: 0,//最大纬度
      minLat: 1000,//最小纬度
      zoom: 4, //地图缩放级别
      mapCenter: null,//地图中心点
      map: null,//地图
      cluster: null,
      info: {},
      carDevCount:{
        carCount: 0,
        onlineCount: 0
      },
      // 视频播放
      videoPlayParams: {
        carDevId: null,
        vedioChnNum: null,
        streamType: null,
        simNo: null
      },
      isFullscreen: false,//是否全屏
      infoWindowShow: false,
      videoWindowShow: false
    };
  },
  watch: {
  },
  created() {
    this.initMap();
  },
  mounted() {
    this.screenfullInit();
  },
  beforeDestroy() {
    this.screenfullDestroy();
    this.doMapClear();
    // 组件销毁前可销毁地图实例
    this.map && this.map.destroy();
  },
  methods: {
    renderMarker(context) {
      let datum = context.data[0];
      let icon = gaodeUtil.createIcon({image: datum.imgPath});
      context.marker.setIcon(gaodeUtil.createIcon({image: datum.imgPath}));
      context.marker.setExtData(datum);
      context.marker.setLabel({
        offset: new AMap.Pixel(-66, 30),
        content: "<div>" + datum.vehicleId + "<div>"
      });
      context.marker.setAngle(datum.direction);
      let size = icon.getSize();
      context.marker.setOffset(new AMap.Pixel(-(parseInt(size[0]) / 2), -parseInt(size[1])));
      context.marker.on('click', (e) => {
        this.info = e.target.getExtData();
        this.infoWindowShow = true;
        this.videoWindowShow = false;
        this.infoWindow.open(this.map, e.target.getPosition());
      })
    },
    parentHandleVideo(simNo,channel,longitude,latitude){
      this.videoPlayParams.carDevId = null;
      this.videoPlayParams.vedioChnNum = channel;
      this.videoPlayParams.streamType = "1";
      this.videoPlayParams.simNo = simNo;
      carDevAndVedioPlay(this.videoPlayParams).then(response => {
        const responseData = response.data;
        const playUrl = "http://" + responseData.sinkIP + ":" + responseData.sinkPlayPort + responseData.playRelativeUrl;
        console.log("playUrl==="+playUrl);
        this.infoWindowShow = false;
        this.videoWindowShow = true;
        this.videoWindow.open(this.map, new AMap.LngLat(longitude,latitude));
        $("#video").empty();
        const flvPlayer = new FLVPlayer({
          container: $('#video'),
          url: playUrl,
          // 自动快进追祯，但是可能会导致画面停顿
          autoFastForward: false
        });
        flvPlayer.play();
      });
    },
    doMapClear() {
      if (this.cluster) {
        this.cluster.setMap(null);
      }
      if (window.pathSimplifierIns) {
        //通过该方法清空上次传入的轨迹
        window.pathSimplifierIns.setData([]);
      }
      //清楚地图上的覆盖物
      this.map.clearMap();
    },
    handleQuery(){
      getAllCarDev().then(response => {
        let rows = response.data;
        this.carDevCount.carCount = rows.length;
      });
      getOnlineCarDev().then(response => {
        this.doMapClear();
        let rows = response.data;
        this.carDevCount.onlineCount = rows.length;
        let markers = [];
        rows.forEach(d => {
          if (d.longitude !== null && d.latitude !== null && Number(d.longitude) !== 0 && Number(d.latitude) !== 0) {
            let position = [];
            position.push(Number(d.longitude), Number(d.latitude));
            d.lnglat = position;
            d.longitude = Number(d.longitude);
            d.latitude = Number(d.latitude);
            if(d.longitude > this.maxLng){
              this.maxLng = d.longitude;
            }
            if(d.longitude < this.minLng){
              this.minLng = d.longitude;
            }
            if(d.latitude > this.maxLat){
              this.maxLat = d.latitude;
            }
            if(d.latitude < this.minLat){
              this.minLat = d.latitude;
            }
            d.imgPath = require('@/assets/images/3-car.png');
            markers.push(d);
          }
        });
        const cenLng = (this.maxLng + this.minLng) / 2;
        const cenLat = (this.maxLat + this.minLat) / 2;
        this.zoom = this.setZoom(this.maxLng, this.minLng, this.maxLat, this.minLat);
        this.mapCenter = [cenLng, cenLat];
        this.cluster = new AMap.MarkerCluster(this.map, markers, {
          gridSize: 60, // 设置网格像素大小
          renderMarker: this.renderMarker, // 自定义非聚合点样式
        });
        this.map.setZoomAndCenter(this.zoom, this.mapCenter);
        this.cluster.on('click', (item) => {
          let num = parseInt(item.marker.dom.outerText);
          if (!isNaN(num) && num > 1) {
            let curZoom = this.map.getZoom();
            if (curZoom < 20) {
              curZoom += 2;
            }
            this.map.setZoomAndCenter(curZoom, item.lnglat);
          }
        });
      })
    },
    //根据经纬极值计算绽放级别。
    setZoom(maxLng, minLng, maxLat, minLat) {
      const zoombuff = ["5000", "10000", "50000", "100000", "300000", "500000", "1000000", "2000000", "3000000",
        "4000000", "5000000", "6000000", "7000000", "8000000"];//级别13到1。
      var pointA = new AMap.LngLat(maxLng, maxLat);  // 创建点坐标A
      var distance = pointA.distance([minLng, minLat]).toFixed(1);//获取两点距离,保留小数点后1位
      for (var i = 0, zoomLen = zoombuff.length; i < zoomLen; i++) {
        if (Number(zoombuff[i]) - Number(distance) > 0) {
          return 13 - i;
        }
      }
      return 8;
    },
    initMap(){
      AMapLoader.load(gaodeUtil.loadOption({
        plugins: ['AMap.ToolBar', 'AMap.Driving', 'AMap.MouseTool', 'AMap.PolygonEditor', 'AMap.MarkerClusterer'],
      })).then((AMap) => {
        this.map = new AMap.Map("map-board", gaodeUtil.initOption({center:this.mapCenter,zoom: this.zoom}));
        //自定义信息窗体
        this.infoWindow = gaodeUtil.createInfoWindow({content: this.$refs.infoWindow,offset: new AMap.Pixel(-300, -220)})
        this.videoWindow = gaodeUtil.createVideoInfoWindow({content: this.$refs.videoWindow,offset: new AMap.Pixel(-200, -390)})
        this.map.setFitView();
        this.handleQuery();
      }).catch(e => {
        console.log(e);
      })
    },
    //刷新数据
    refreshClick() {
      this.handleQuery();
    },
    screenfullChange() {
      this.isFullscreen = screenfull.isFullscreen;
    },
    screenfullInit() {
      if (screenfull.isEnabled) {
        screenfull.on('change', this.screenfullChange)
      }
    },
    screenfullDestroy() {
      if (screenfull.isEnabled) {
        screenfull.off('change', this.screenfullChange)
      }
    },
    //全屏
    screenfullClick() {
      const elem = this.$refs.fullscreenDiv;
      if (elem.requestFullscreen) {
        if(this.isFullscreen){
          document.exitFullscreen();
        }else {
          elem.requestFullscreen();
        }
      } else if (elem.mozRequestFullScreen) { // Firefox
        if(this.isFullscreen){
          document.mozCancelFullScreen();
        }else {
          elem.mozRequestFullScreen();
        }
      } else if (elem.webkitRequestFullscreen) { // Chrome, Safari and Opera
        if(this.isFullscreen){
          document.webkitExitFullscreen();
        }else {
          elem.webkitRequestFullscreen();
        }
      } else if (elem.msRequestFullscreen) { // IE/Edge
        if(this.isFullscreen){
          document.msExitFullscreen();
        }else {
          elem.msRequestFullscreen();
        }
      }
    }
  }
};
</script>

<style scoped lang="scss">

.amap-marker-label {
  border: none;
  background-color: #0e9aef;
  border-radius: 15px;
}
::v-deep .amap-marker-label {
  border: none;
  background-color: #0e9aef;
  border-radius: 15px;
}
.aside-container {
  height: calc(100vh - 84px);
  background-color: #fff;
}
.main_cont {
  position: relative;
  margin: 0;
  padding: 0;
  background-color: #fff ;
  height: 100vh;
  overflow: hidden;
  border-left: solid 1px #e8e8e8;
}
.full-screen-cancel{
  position: absolute;
  top: 100px;
  right: 5px;
  opacity: 0.8;
  font-size: 20px;
}

.full-screen{
  position: absolute;
  top: 16px;
  right: 5px;
  opacity: 0.8;
  font-size: 20px;
}

.refresh-full-screen-cancel{
  position: absolute;
  opacity: 0.8;
  right: 31px;
  font-size: 28px;
  top: 96px;
}

.refresh-full-screen{
  position: absolute;
  top: 12px;
  right: 31px;
  opacity: 0.8;
  font-size: 28px;

}

.input-item-total-full-screen-cancel {
  position: absolute;
  background-color: #65aaf1;
  padding: 5px 20px 10px;
  top: 100px;
  border: 1px dashed #999;
  opacity: 0.8;
  margin-left: 15px;
  border-radius: 5px;

  .label {
    color: #fff;
    line-height: 20px;
    font-size: 14px;
  }

  .itemValue {
    color: #ffd9a3;
    line-height: 20px;
    font-size: 14px;
    margin-left: 10px;
  }
}

.input-item-total-full-screen {
  position: absolute;
  background-color: #65aaf1;
  padding: 5px 20px 10px;
  top: 16px;
  border: 1px dashed #999;
  opacity: 0.8;
  margin-left: 15px;
  border-radius: 5px;

  .label {
    color: #fff;
    line-height: 20px;
    font-size: 14px;
  }

  .itemValue {
    color: #ffd9a3;
    line-height: 20px;
    font-size: 14px;
    margin-left: 10px;
  }
}
</style>

